<?php

/**
 * Created by PhpStorm.
 * User: kc
 * Date: 2017/12/15
 * Time: 14:55
 */
class AllActivityController extends BaseController{
    /**
     * @Author:      kc
     * @DateTime:    2017-12-15 15:12:00
     * @Description: 2017双旦活动
     */
    public function double_dan_check(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            //检测活动的信息
            $activity = ActivityBaseInfo::find(Config::get("config.double_dan_activity_id"));
            $check_activety = ActivityBaseInfo::checkAward($activity,$response);//检测活动的信息
            if(is_null($check_activety)){
                break;
            }

            //检查神州租车 和 京B车牌
            if(in_array($wechat_user->id,Config::get("config.shenzhou_huodong_user_id"))){
                $response = Lang::get('error.activity_taxi_not_participate_51012');
                break;
            }
            //企业用户
            if($wechat_user->type == 2){
                $response = Lang::get('error.activity_taxi_not_participate_51012');
                break;
            }
            //检查自己参加过活动没有
            $ao = ActivityOrder::where("activity_id",$activity->id)->where("user_id",$wechat_user->id)->first();
            if($ao){
                $activity_award = ActivityAward::where('prize_type',0)->where('id',$ao->award_id)->first();
                if($activity_award){
                    $coupon_count = Coupons::where("coupon_base_info_id",$activity_award->prize_id)
                        ->where('received_user_id',$wechat_user->id)
                        ->count();
                    if($coupon_count > 0){
                        $response = Lang::get('error.activity_award_already_receive_51015');
                        break;
                    }
                }
            }

            if($ao){//如果存在 提示已经抽过奖了
                $aw_success= DB::select("SELECT aw.*,aoa.is_check,aoa.sort FROM `activity_order_award` aoa LEFT JOIN activity_award aw on aw.id=aoa.award_id where aoa.activity_order_id=? order by aoa.sort " ,array($ao->id));//查出中奖的顺序
                foreach ($aw_success as $_aw) {
                    switch ($_aw->name) {
                        case '一等奖':
                            $_aw->qian_number=1;
                            break;
                        case '二等奖':
                            $_aw->qian_number=2;
                            break;
                        case '三等奖':
                            $_aw->qian_number=3;
                            break;
                        case '四等奖':
                            $_aw->qian_number=4;
                            break;
                        case '五等奖':
                            $_aw->qian_number=5;
                            break;
                        default:
                            $_aw->qian_number=1;
                            break;
                    }
                }
                $check_aw = ActivityAward::find($ao->award_id);
                    switch ($check_aw->name) {
                        case '一等奖':
                            $check_aw->qian_number=1;
                            break;
                        case '二等奖':
                            $check_aw->qian_number=2;
                            break;
                        case '三等奖':
                            $check_aw->qian_number=3;
                            break;
                        case '四等奖':
                            $check_aw->qian_number=4;
                            break;
                        case '五等奖':
                            $check_aw->qian_number=5;
                            break;
                        default:
                            $check_aw->qian_number=1;
                            break;
                    }
                $response =  Lang::get("error.activity_award_order_already_51014");
                $response['result']['aw_success'] = $aw_success;
                $response['result']['check_aw'] = $check_aw;
                break;
            }

            //检查订单信息
            $order = Orders::where("user_id",$wechat_user->id)
                ->whereIn("status",Orders::$complete)
                ->whereBetween('created_at',array($activity->begin_date,$activity->end_date))
                ->whereBetween('pay_time',array($activity->begin_date,$activity->end_date))
                ->where('payable_amount',">=",20000)
                ->orderBy("pay_time")
                ->get();
            $order_array = array();
            foreach ($order as $_order) {
                if(!(strpos(strtoupper($_order->car_no),"京B") === 0)){
                    $ao = ActivityOrder::where("activity_id",$activity->id)
                        ->where("order_id",$_order->order_id)
                        ->first();//查看没中奖的 信息
                    if(!$ao){
                        $order_array[] = $_order;
                        break;
                    }
                }
            }
            if(sizeof($order_array) <= 0){
                $response = Lang::get('error.activity_not_order_error_51013');
                break;
            }

            $activity_coupon_info  = ActivityAward::where('award_group_id',$activity->award_group)->get();//传出奖项 其实也可不传出
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'activity_coupon_info' => $activity_coupon_info,
                    'activity' => $activity,
                    'order' => $order[0],
                )
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "double_dan/check", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-12-16 10:00:00
     * @Description: 抽奖
     * 传入 活动id activity_id 和抽奖的订单 order_id  抽中的位置是 0-9 number 类型 抽奖类型
     */
    public function luckDraw(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'number' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wechat_user = $this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }

            $activity = ActivityBaseInfo::find(Config::get("config.double_dan_activity_id"));
            //检测活动的信息
            $check_activety = ActivityBaseInfo::checkAward($activity,$response);
            if(is_null($check_activety)){
                break;
            }
            //检查订单信息
            $order = Orders::where('order_id',Input::get("order_id"))
                ->where("user_id",$wechat_user->id)
                ->first();
            //TODO::稍后修改
            $order_check = ActivityBaseInfo::isCanUserActivity($order,$activity,$response);   //检查订单活动信息
            if(is_null($order_check)){
                break;
            }
            //查看订单是否抽过奖
            $ao = ActivityOrder::where("activity_id",$activity->id)->where("order_id",$order->order_id)->first();
            if($ao){
                $activity_award = ActivityAward::where('prize_type',0)->where('id',$ao->award_id)->first();
                if($activity_award){
                    $coupon_count = Coupons::where("coupon_base_info_id",$activity_award->prize_id)
                        ->where('received_user_id',$wechat_user->id)
                        ->count();
                    if($coupon_count > 0){
                        $response = Lang::get('error.activity_award_already_receive_51015');
                        break;
                    }
                }
            }

            if($ao){//如果存在 提示已经抽过奖了
                $aw_success= DB::select("SELECT aw.*,aoa.is_check,aoa.sort FROM `activity_order_award` aoa LEFT JOIN activity_award aw on aw.id=aoa.award_id where aoa.activity_order_id=? order by aoa.sort " ,array($ao->id));//查出中奖的顺序
                foreach ($aw_success as $_aw) {
                    switch ($_aw->name) {
                        case '一等奖':
                            $_aw->qian_number=1;
                            break;
                        case '二等奖':
                            $_aw->qian_number=2;
                            break;
                        case '三等奖':
                            $_aw->qian_number=3;
                            break;
                        case '四等奖':
                            $_aw->qian_number=4;
                            break;
                        case '五等奖':
                            $_aw->qian_number=5;
                            break;
                        default:
                            $_aw->qian_number=1;
                            break;
                    }
                }
                $check_aw = ActivityAward::find($ao->award_id);
                switch ($check_aw->name) {
                    case '一等奖':
                        $check_aw->qian_number=1;
                        break;
                    case '二等奖':
                        $check_aw->qian_number=2;
                        break;
                    case '三等奖':
                        $check_aw->qian_number=3;
                        break;
                    case '四等奖':
                        $check_aw->qian_number=4;
                        break;
                    case '五等奖':
                        $check_aw->qian_number=5;
                        break;
                    default:
                        $check_aw->qian_number=1;
                        break;
                }
                $response =  Lang::get("error.activity_award_order_already_51014");
                $response['result']['aw_success'] = $aw_success;
                $response['result']['check_aw'] = $check_aw;
                break;
            }
            //开始抽奖
            $activity_coupon_info  = ActivityAward::where('award_group_id',$activity->award_group)->get();//获取奖项
            $rand_array = array();//抽奖的 概率数组
            $jiangxaing_array = array();//奖项的数组
            $probability = '';
            foreach ($activity_coupon_info as $a) {
                $rand_array[$a->id] = $a->probability;
                $probability += $a->probability;
                $jiangxaing_array[] = $a;
            }
            if($probability == 0){
                $response = Lang::get("error.activity_not_exist");
                break;
            }
            $id = Common::random($rand_array);//抽中的奖项 id 为
            $temp_aw=ActivityAward::find($id);//暂时的奖项
            //检查奖项的数量
            $aw_count = ActivityOrder::where("activity_id",$activity->id)->where("award_id",$id)->count();
            if($aw_count >= $temp_aw->max_number){//超过数量了 不中奖或者选最大概率的 奖项
                $temp_aw = ActivityAward::where('award_group_id',$activity->award_group)
                    ->orderBy("probability","desc")->orderBy('max_number','desc')
                    ->first();
            }
            if($temp_aw->prize_type == 0){
                $c = Coupons::where("coupon_base_info_id",$temp_aw->prize_id)->where("status",1)->first();
                if(is_null($c)){
                    $response = Lang::get("error.coupon_has_been_brought_out_51008");
                    break;
                }
            }

            //最终的奖项 信息
            $ao = new ActivityOrder();
            $ao->activity_id = $activity->id;
            $ao->user_id = $wechat_user->id;
            $ao->order_id = $order->order_id;
            $ao->award_id = $temp_aw->id;
            $ao->save();
            $aoa = new ActivityOrderAward();
            $aoa->activity_order_id=$ao->id;
            $aoa->award_id=$temp_aw->id;
            $aoa->sort=Input::get("number");
            $aoa->is_check=1;
            $aoa->save();
            for ($i=0; $i <9; $i++) {
                if($i!=Input::get("number")){
                    $t_t = $jiangxaing_array[mt_rand(0,count($jiangxaing_array)-1)];
                    $aoa = new ActivityOrderAward;
                    $aoa->activity_order_id = $ao->id;
                    $aoa->award_id = $t_t->id;
                    $aoa->sort = $i;
                    $aoa->is_check = 0;
                    $aoa->save();
                }
            }

            $aw_success = DB::select("SELECT aw.*,aoa.is_check,aoa.sort FROM `activity_order_award` aoa LEFT JOIN activity_award aw on aw.id=aoa.award_id where aoa.activity_order_id=? order by aoa.sort " ,array($ao->id));
            foreach ($aw_success as $_aw) {
                switch ($_aw->name) {
                    case '一等奖':
                        $_aw->qian_number=1;
                        break;
                    case '二等奖':
                        $_aw->qian_number=2;
                        break;
                    case '三等奖':
                        $_aw->qian_number=3;
                        break;
                    case '四等奖':
                        $_aw->qian_number=4;
                        break;
                    case '五等奖':
                        $_aw->qian_number=5;
                        break;
                    default:
                        $_aw->qian_number=1;
                        break;
                }
            }
            $selected_award = ActivityAward::where('id',$ao->award_id)->first();
            switch ($selected_award->name) {
                case '一等奖':
                    $selected_award->qian_number=1;
                    break;
                case '二等奖':
                    $selected_award->qian_number=2;
                    break;
                case '三等奖':
                    $selected_award->qian_number=3;
                    break;
                case '四等奖':
                    $selected_award->qian_number=4;
                    break;
                case '五等奖':
                    $selected_award->qian_number=5;
                    break;
                default:
                    $selected_award->qian_number=1;
                    break;
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    "ao" => $ao,
                    "aw_success" => $aw_success,
                    'selected_award' => $selected_award
                )
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "double_dan/luckDraw", 'input' =>Input::all() ,"output" => $response));
        return  json_encode($response);
    }
    /**
     * @Author:      kc
     * @DateTime:    2017-12-16 15:24:00
     * @Description: 领取奖项
     */
    public function receive(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $wechat_user = $this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            $activity = ActivityBaseInfo::find(Config::get("config.double_dan_activity_id"));
            //检测活动的信息
            $check_activety = ActivityBaseInfo::checkAward($activity,$response);
            if(is_null($check_activety)){
                break;
            }
            $activity_order = ActivityOrder::where('activity_id',$activity->id)->where('user_id',$wechat_user->id)->first();
            $activity_award = ActivityAward::where('prize_type',0)->where('id',$activity_order->award_id)->first();
            if($activity_award){
                $coupon_count = Coupons::where("coupon_base_info_id",$activity_award->prize_id)
                    ->where('received_user_id',$wechat_user->id)
                    ->count();
                if($coupon_count > 0){
                    $response = Lang::get('error.activity_award_already_receive_51015');
                    break;
                }
                $c = Coupons::where("coupon_base_info_id",$activity_award->prize_id)->where("status",1)->first();
                if(is_null($c)){
                    return Lang::get("error.coupon_has_been_brought_out_51008");
                }
                $c->received_user_id = $wechat_user->id;
                $coupon_base_info = DB::table('coupon_base_info')->where('id',$activity_award->prize_id)->first();
                $c->get_time = date("Y-m-d H:i:s",time());
                if($coupon_base_info->date_type == 1){
                    $c->end_date = date("Y-m-d",strtotime("+".$coupon_base_info->date_num." day"));
                }
                $c->status = 2;
                $c->save();
            }
            $response = array(
                'code' => 0,
                'msg' => 'ok',
            );
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "double_dan/receive", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /*
    * @Author:      kc
    * @DateTime:    2017-12-20 17:50:00
    * @Description:唐钢用户注册活动
    * */
    public function tg_register(){
        $validator = Validator::make(Input::all(),
            array(
                "phone" => "required",
                "check_code" => "required",
                'register_source_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result' => array());
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $area = '010';
            $record = UserCheckCode::getCheckCode(Input::get('phone'),$area);
            if (is_null($record)) { //没有记录
                $response = Lang::get("error.user_login_checkcode_null_10004");
                break;
            }
            //校验是否超过时限
            if (time() > Common::datetime2Num($record->out_time_at)) {
                $response = Lang::get("error.user_login_checkcode_timeout_10005");
                break;
            }
            //校验验证码是否正确
            if ($record->check_code != Input::get('check_code')) {
                $response = Lang::get("error.user_login_checkcode_error_10006");
                break;
            }

            //根据活动查到活动有效期
            /*$activity = Coupons::getActivityBaseInfo(Config::get('c_config.tg_activity_id'));
            $activity_dateline =  ActivityBaseInfo::checkActivity($activity,$response);
            if(is_null($activity_dateline)){
                break;
            }*/
            $wechat = Users::getUser(Input::get('phone'));
            if(is_null($wechat)){
                try{
                    $wechat = new Users();
                    $wechat->phone = Input::get('phone');
                    $wechat->status = 1;
                    $wechat->register_source_id = Input::get('register_source_id');//1-微站 2-app 14-门店
                    $wechat->real_name = '';
                    $wechat->sex = 0;
                    $wechat->area = '010';
                    $wechat->type = 1;
                    $wechat->activate = 1;
                    $wechat->nickname = '';
                    $wechat->heading_img = '';
                    $wechat->member = Config::get('user.def_member');
                    $wechat->save();

                    $label_activity = UserLabelActivity::where('user_id',$wechat->id)->count();
                    if($label_activity > 0){
                        $user_label_activity = new UserLabelActivity();
                        $user_label_activity->user_id = $wechat->id;
                        $user_label_activity->lable_id = Config::get('c_config.tang_gang_label_activity_type');
                        $user_label_activity->created_by = $wechat->id;
                        $user_label_activity->save();
                    }
                }catch (Exception $e){
                    Log::error("error", array("system" => "wechat2.0" ,"event" => "coupon_receive", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("error.login_create_token_error_21005");
                    break;
                }
            }

            if($wechat->status == 2){
                $response = Lang::get('error.user_frozen_error_21002');
                break;
            }


            //如果发现此用户是老用户，且未激活 直接激活
            if($wechat->type == 1 && $wechat->activate == 0) {
                $wechat->activate = 1;
                $wechat->save();

            }
            $label_activity = UserLabelActivity::where('user_id',$wechat->id)->count();
            if($label_activity == 0){
                $user_label_activity = new UserLabelActivity();
                $user_label_activity->user_id = $wechat->id;
                $user_label_activity->lable_id = Config::get('c_config.tang_gang_label_activity_type');
                $user_label_activity->created_at = date("Y-m-d H:i:s",time());
                $user_label_activity->created_by = $wechat->id;
                $user_label_activity->save();
            }

            try{
                $token="";
                $find_token = UserTokens::where('user_id',$wechat->id)->first();
                if(!is_null($find_token)){ //有token 判断token是否过期
                    if(strtotime($find_token->out_time_at) < time()){//说明过期了
                        UserTokens::where('user_id',$wechat->id)->delete();
                        $user_token = new UserTokens;
                        $user_token->user_id = $wechat->id;
                        $user_token->token = md5(Input::get('phone').time().rand(0,100));
                        $user_token->created_at = Common::num2DateTime(time());
                        $user_token->out_time_at = Common::num2DateTime(time() + Config::get("user.token_time_out"));
                        $user_token->save();
                        $token=$user_token->token;
                    }else{
                        $token=$find_token->token;
                    }
                }else{
                    $user_token = new UserTokens;
                    $user_token->user_id = $wechat->id;
                    $user_token->token = md5(Input::get('phone').time().rand(0,100));
                    $user_token->created_at = Common::num2DateTime(time());
                    $user_token->out_time_at = Common::num2DateTime(time() + Config::get("user.token_time_out"));
                    $user_token->save();
                    $token=$user_token->token;
                }

            } catch (Exception $e){
                Log::error("error", array("system" => "wechat2.0" ,"event" => "coupon_receive", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.login_create_token_error_21005");
                break;
            }
            $response["result"] = array(
                "user_info" => array(
                    'id'=> $wechat->id,
                    'token' => $token,
                    'phone' => $wechat->phone,
                    'real_name' => $wechat->real_name,
                    'sex' => $wechat->sex,
                    'area' => $wechat->area,
                    'remark' => $wechat->remark,
                    'type' => $wechat->type,
                    'status' =>$wechat->status,
                    'nickname' => $wechat->nickname,
                    'birthday' => $wechat->birthday,
                    'heading_img' =>  $wechat->heading_img,
                    'heading_img_url' =>  Config::get('config.heading_img_url'),
                ),
            );

        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "tg_register", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}